package com.example.servicegateway.authentication.component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.demo.common.constants.AuthModel;
import com.demo.common.constants.AuthRedisKey;
import com.example.servicegateway.entity.TokenInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

@Slf4j
@Component(AuthModel.AUTHORIZATION_CODE)
public class AuthorizationCodeAuthComponent extends AuthComponent {
    @Override
    protected String getRedisTokenKey(String userId) {
        return AuthRedisKey.authorizationCodeTokenKey(userId);
    }

    @Override
    protected boolean grant(TokenInfo tokenInfo, String authority, String path) {
        String userId = tokenInfo.getUserId();
        String json = stringRedisTemplate.opsForValue().get(AuthRedisKey.authorizationCodeUserInterfaceKey(userId));
        if (StringUtils.isBlank(json)) {
            log.info("用户id={}没有配置访问接口", userId);
            return false;
        }
        JSONArray jsonArray = JSON.parseArray(json);
        for (Object obj : jsonArray) {
            JSONObject jsonObject = (JSONObject) obj;
            String url = jsonObject.getString("url");
            if (StringUtils.equals(url, path)) {
                log.info("url={}匹配成功", url);
                return true;
            }
        }
        log.info("没有匹配url={}", path);
        return false;
    }
}
